package com.spring.mail;

import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.spring.domain.User;

public class MailService {

	   private static JavaMailSender mailSender;
	   private static VelocityEngine velocityEngine;

	   public void setMailSender(JavaMailSender mailSender) {
	      MailService.mailSender = mailSender;
	   }

	   public void setVelocityEngine(VelocityEngine velocityEngine) {
	      MailService.velocityEngine = velocityEngine;
	   }

	   public void sendRegistrationEmail(User user) {

	      // Do the registration logic...

		   sendRegistration(user);
	   }

	   public static void sendRegistration(final User user) {
		   
	      MimeMessagePreparator preparator = new MimeMessagePreparator() {

	         public void prepare(MimeMessage mimeMessage) throws Exception {
	            MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
	            message.setSubject("Subject");
	            message.setTo("marcopogo81@gmail.com");
	            message.setFrom("sito_admin@blackmore.com"); 
	            Map<String,Object> model = new HashMap<String,Object>();
	            model.put("user", user);
	            
	            //model.put("messages", value);
	            
	            
	            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/com/spring/mail/resource/registration.vm", model);
	            message.setText(text, true);
	         }
	      };
	      
	      mailSender.send(preparator);
	   }
}
